package com.you.common.handler;

import com.you.common.exception.UserException;
import com.you.common.model.Response;
import com.you.common.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import static com.you.common.enums.ResponseEnum.UNKNOWN_ERROR;

/**
 *<p>
 *统一异常处理
 *</p>
 *
 * @author : liu.yang.
 * @date : 2018-07-09 星期一 08:08:01
 * @since : 1.0.0
 */
@ControllerAdvice
public class ExHandler {
    private final static Logger LOG = LoggerFactory.getLogger(ExHandler.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Response handle(Exception e){
        if(e instanceof UserException){
            UserException userException = (UserException) e;
            return ResponseUtil.error(userException.getCode(), userException.getMessage());
        }else {
            LOG.error("[系统异常]"+e.getMessage(),e);
            return ResponseUtil.error(UNKNOWN_ERROR.getCode(), UNKNOWN_ERROR.getMsg());
        }
    }
}
